package Oct.Leaves;


public class L {
    public static void main(String[] args) {
        String test = "rrryyyrryyyrr";
        Solution s = new Solution();
        int i = s.minimumOperations(test);
        System.out.println(i);
    }
}

// LCP 19. 秋叶收藏集
class Solution_five {

    public int minimumOperations(String leaves) {
        int min = Integer.MAX_VALUE;
        int tmp =0;
        int  end = 0;
        if(leaves.charAt(0)!='r') end++;
        if(leaves.charAt(leaves.length()-1)!='r')end++;

        int left = 1;
        int right =leaves.length()-2;
        while(left<leaves.length()&&leaves.charAt(left)=='r') left++;
        while(right>=0&&leaves.charAt(right)=='r') right--;


        int[] r= new int[leaves.length()];
        // int[] y=new int[leaves.length()];
        r[0] = leaves.charAt(0)=='r'?1:0;
        // y[0] = leaves.charAt(0)=='y'?1:0;
        for(int i=1;i<leaves.length();i++){
            if(leaves.charAt(i)=='r'){
                r[i]=r[i-1]+1;
                // y[i]=y[i-1];
            } 
            else {
                r[i]=r[i-1];
                // y[i]=y[i-1]+1;
            }
        }   
        for(int i= left;i<leaves.length();i++){
            for(int j=right;j>=i;j--){
                    tmp = 0;
                    tmp+=(i-1-0-(r[i-1]-r[0])); //i-1->1
                    tmp+=(leaves.length()-2-j-(r[leaves.length()-2]-r[j]));     //len-2 -> j+1
                    // tmp+=(j-i+1-(y[j]-y[i-1]));
                    tmp+=(r[j]-r[i-1]);
                    min = Math.min(min,tmp);
                
            }
        }
        return min==Integer.MAX_VALUE?leaves.length()-2+end:min+end;
    }
}



class Solution {
    public int minimumOperations(String leaves) {
        final int len = leaves.length();
        int[] ans =  new int[3];
        // ans[0][0] = leaves.charAt(0)=='r'?0:1;
        ans[0] = leaves.charAt(0)=='r'?0:1;
        // ans[0][1] = ans[0][2] = Integer.MAX_VALUE/2;
        ans[1] = ans[2] = Integer.MAX_VALUE/2;
        for(int i=1;i<len;i++){
            int toRed = leaves.charAt(i)=='r'?0:1;
            int toYellow = leaves.charAt(i)=='y'?0:1;
            int _0 = ans[0];
            int _1 = ans[1];
            int _2 = ans[2];
            ans[0] = _0 + toRed;
            ans[1] = Math.min(_0, _1)+ toYellow;
            ans[2] = Math.min(_1,_2) + toRed;
        }
        return ans[2];
    }
}